/*
   This acts as a mixin to place widgets based off of noBuisnessBase/form/WidgetBase into a real dijit/Form
*/


define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'dojo/_base/array',
      'dojo/Evented',
      'dojo/dom-construct',
      'dojo/on',
      'dojo/json',
      'dijit/form/Form',
      'dijit/Tooltip'
   ],
   function(declare, lang, array, evented, domConstruct, on, JSON, Form, Tooltip)
   {
      return declare([Form, evented],
      {
         mAutoPublish: true,
         enctype: 'multipart/form-data',
         postscript: function(args)
         {
            this.inherited(arguments);
            this.mToolTips = [];
         },
         addWidget: function(pWidget)
         {
            domConstruct.place(pWidget.domNode, this.domNode, "only");
            this.own(
               on(this.domNode, "submit", lang.hitch(this, function(pEvent)
               {
                  dojo.stopEvent(pEvent);
                  if(this.validate())
                  {
                     if(pWidget.emitFormExecuted)
                     {
                        if(!pWidget.mEmitted)
                           pWidget.mEmitted = pWidget.emitFormExecuted();
                     }
                  }
                  else
                  {
                     // put this in a tiemout so that any dojox busy buttons in the from can be snapped back to non busy state in the postSubmit call
                     setTimeout(lang.hitch(pWidget, "postSubmit", {}, true), 1);
                  }
               })),
               pWidget.on("formExecuted", lang.hitch(this, function(data)
               {
                  if(this.mAutoPublish)
                     dojo.publish("global:AjaxResult", [data]);
               
                  this.emit("formExecuted", data);
               })),
               pWidget.on("formExecutedButNotSaved", lang.hitch(this, function(data)
               {
                  this.emit("formExecutedButNotSaved", data);
               })),
               pWidget.on("formCanceled", lang.hitch(this, function(data)
               {
                  this.emit("formCanceled", data);
               })),
               pWidget.on("formSubmit", lang.hitch(this, function()
               {
                  this.submitForm();
               })),
               pWidget.on('loaded', lang.hitch(this, function()
               {
                  this.emit('loaded');
               }))
            );

            this.mWidget = pWidget;
         },
         destroy: function()
         {
            this.inherited(arguments);
            if(this.mWidget)
               this.mWidget.destroy();

            this.mWidget = null;
         },
         submitForm: function()
         {
            dojo.forEach(this.mToolTips, function(pToolTip, i)
            {
               pToolTip.destroyRecursive();
            }, this);
            var xhrArgs = {
               form: this.domNode,
               url: this.action,
               handleAs: "json",
               failOk: true,
               load: lang.hitch(this, function(data){
                  this.postSubmit(data, false);
               }),
               error: lang.hitch(this, function(error)
               {
                  var data = JSON.parse(error.responseText);

                  array.forEach(this.mWidget.mChildWidgets, lang.hitch(this, function(pWidget){
                     if(!data)
                        return;

                     // Display errors on widgets
                     for(var i in data.extraInfo)
                     {
                        if(!data.extraInfo.hasOwnProperty(i))
                           continue;

                        if(pWidget.name != i)
                           continue;

                        // Set pWidget to error state
                        pWidget.state = "Error";
                        pWidget._setStateClass();
                        dijit.setWaiState(pWidget.focusNode, "invalid", "true");

                        // get message
                        var msg = "";
                        if(data.extraInfo[i].length !== null)
                        {
                           for(var m in data.extraInfo[i])
                           {
                              if(!data.extraInfo[i].hasOwnProperty(m))
                                 continue;

                              msg = data.extraInfo[i][m];
                           }
                        }
                        else
                           msg = data.extraInfo[i];

                        // Set tooltip if message exists
                        if(msg !== "")
                        {
                           var toolTip = new Tooltip({
                              connectId: pWidget.domNode,
                              label: msg,
                              showDelay: 0
                           });
                           this.mToolTips.push(toolTip);
                        }
                     }

                     console.log(pWidget);
                  }));
                  this.postSubmit(data, true);
               })
            };

            this.preSubmit();

            dojo.xhrPost(xhrArgs);
         },
         preSubmit: function()
         {
            if(this.mWidget && this.mWidget.preSubmit)
               this.mWidget.preSubmit();
         },
         postSubmit: function(data, error)
         {
            if(this.mWidget && this.mWidget.postSubmit)
               this.mWidget.postSubmit(data, error);
         }
      });
   }
);
